<?php

namespace App\Services\SetUserPayCode;

use App\Models\User;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Api\V1\Requests\FormRequest;

class SetUserPayCodeRequest extends FormRequest
{
	public function rules()
	{
		return [
			'old_pay_code' => [
				'bail',
				'nullable',
				'string',
				'min:6',
				'max:20',
			],
			'new_pay_code' => [
				'bail',
				'required',
				'string',
				'min:6',
				'max:20',
				$this->newPayCode()
			],
			'captcha_key' => 'required|string',
			'captcha_code' => 'required|string',
		];
	}

	public function attributes()
	{
		return [
			'old_pay_code' => '旧交易密码',
			'new_pay_code' => '新交易密码',
			'captcha_key' => '图片验证码密钥',
			'captcha_code' => '图片验证码',
		];
	}

	public function newPayCode()
	{
		return function ($key, $value, $fail) {

			/**
			 * @var User $user
			 */
			$user = $this->user();

			$payCodeCanTry = (int)sc('pay_code_can_try');

			if (! $user->isPayCodeSet()) {
				return true;
			}
			if ($user->pay_code and !$this->old_pay_code) {
				return $fail('请输入旧交易密码');
			}
			if ($user->myPayCodeTryCache() >= $payCodeCanTry) {
				return $fail("旧交易密码输错{$payCodeCanTry}次请联系客服");
			}
			if ($this->old_pay_code == $this->new_pay_code) {
				return $fail('新旧交易密码相同');
			}
			if (Hash::check($this->new_pay_code, $user->password)) {
				return $fail('交易密码不可与登录密码相同');
			}
			if (! Hash::check($this->old_pay_code, $user->pay_code)) {
				$leftChance = $user->leftPayCodeTryAfterError();
				return $fail("旧交易密码错误还剩{$leftChance}次机会");
			}
			return true;
		};
	}
}
